/**
 * 牌桌管理器
 */
var CreatorHelper = require('CreatorHelper')
var UnitTools = require('UnitTools')
var NetworkManager = require('NetworkManager')
var UserManager = require('UserManager')
var AudioManager = require('AudioManager')

class TableManager {
    // 人物位置
    static figurePos (pos) {
        var arrayPos = new Array()
        arrayPos[0] = {x: -428, y: 225}
        arrayPos[1] = {x: 399, y: 215}
        arrayPos[2] = {x: 392, y: -80}
        arrayPos[3] = {x: -71, y: -98}
        arrayPos[4] = {x: -381, y: -75}

        return arrayPos[pos]
    }

    // 时钟位置
    static clockPos (pos) {
        var arrayPos = new Array()
        arrayPos[0] = {x: -216, y: 237}
        arrayPos[1] = {x: 293, y: 236}
        arrayPos[2] = {x: 301, y: -124}
        arrayPos[3] = {x: -146, y: -134}
        arrayPos[4] = {x: -458, y: -16}

        return arrayPos[pos]
    }

    // 手牌位置
    static handCardsPos (pos) {
        var arrayPos = new Array()
        arrayPos[0] = {x: -318, y: 126}
        arrayPos[1] = {x: 329, y: 113}
        arrayPos[2] = {x: 254, y: -42}
        arrayPos[3] = {x: 99, y: -42}
        arrayPos[4] = {x: -198, y: -42}

        return arrayPos[pos]
    }

    // 结算对话框当前位置
    static settlementPos (pos) {
        var arrayPos = new Array()
        arrayPos[0] = {y: 95}
        arrayPos[1] = {y: 46}
        arrayPos[2] = {y: -5}
        arrayPos[3] = {y: -53}
        arrayPos[4] = {y: -103}

        cc.log('当前位置:', arrayPos[pos])
        return arrayPos[pos]
    }

    // 确认对话框
    static confirmModel (msg, success) {
        var path = 'prefabs/table/ConfirmModel',
            canvas = cc.find('Canvas')

        CreatorHelper.loadPrefab(path, (node) => {
            canvas.addChild(node)

            var modelNode  = node.getChildByName('model_bg')
            var btnGroupNode = modelNode.getChildByName('btn_group')
            var confirmBtn = btnGroupNode.getChildByName('cancel_bg'),
                cancelBtn  = btnGroupNode.getChildByName('confirm_bg'),
                msgNode = modelNode.getChildByName('content')

            var msgTxt  = msgNode.getComponent(cc.Label)
            msgTxt.string = msg

            CreatorHelper.setNodeClickEvent(confirmBtn, () => {
                canvas.removeChild(node)
                if (success) {
                    success()
                }
            })

            CreatorHelper.setNodeClickEvent(cancelBtn, () => {
                canvas.removeChild(node)
            })
        })
    }

    // 提示框
    static alertModel (msg) {
        var path = 'prefabs/table/Alert',
            canvas = cc.find('Canvas')

        CreatorHelper.loadPrefab(path, (node) => {
            canvas.addChild(node)
            node.active = false
            var msgNode = node.getChildByName('text')
            var msgTxt  = msgNode.getComponent(cc.Label)
            var anim  = node.addComponent(cc.Animation)
            var apath = ['animations/alert']

            CreatorHelper.loadAnimClip(apath, (clip) => {
                anim.addClip(clip[0], 'alert')
                anim.play('alert')
                msgTxt.string = msg
                node.active = true

                setTimeout(() => {
                    if (node.name != '' && canvas.name != '') {
                        canvas.removeChild(node)
                    }
                }, 4000)
            })
        })
    }

    // 显示操作信息
    static showOperMsg (obj) {
        let pos = TableManager.getPosByUid(obj.uid)
        let path = 'prefabs/table/PlayerMsg'
        let canvas = cc.find('Canvas')

        if (!UnitTools.isNullOrUndefined(obj.msg)) {
            CreatorHelper.loadPrefab(path, (node) => {
                canvas.addChild(node)
                node.active = false
                var msgLabel = node.getChildByName('Txt').getComponent(cc.Label)
                var anim  = node.addComponent(cc.Animation)
                var apath = ['animations/playerMsg']
                var hpos = TableManager.handCardsPos(pos)
                if (!UnitTools.isNullOrUndefined(hpos)) {
                    node.x = hpos.x
                    node.y = hpos.y
                }

                msgLabel.string = obj.msg
                TableManager.playOperSound(obj.msg)
                CreatorHelper.loadAnimClip(apath, (clip) => {
                    anim.addClip(clip[0], 'player')
                    anim.play('player')
                    node.active = true

                    setTimeout(() => {
                        if (node.name != '' && canvas.name != '') {
                            canvas.removeChild(node)
                        }
                    }, 2500)
                })
            })
        }
    }

    // 播放音效
    static playOperSound (msg) {
        var name = ''
        if (msg == '过牌') {
            name = 'guopai'
        } else if (msg == '跟注') {
            name = 'genzhu'
        } else if (msg == '弃牌') {
            name = 'qipai'
        } else if (msg == '加注') {
            name = 'jiazhu'
        }
        if (name != '') {
            AudioManager.playSound(name)
        }
    }

    // 根据uid获取pos
    static getPosByUid (uid) {
        for (let i in TableManager.user) {
            if (TableManager.user[i].uid == uid) {
                return i
            }
        }
        return null
    }

    // 添加人物节点
    static addFigureNode (user, node, prefab) {
        cc.log('添加人物')
        for (let k in user) {
            let idx = parseInt(k)
            let item = cc.instantiate(prefab)
            let data = {
                uid: user[idx]['uid'],
                head: idx,
                username: user[idx]['name'],
                balance: user[idx]['balance'],
                bet: user[idx]['bet'],
                realyStatus: user[idx]['status'],
                pos: idx
            }
            let pos = TableManager.figurePos(idx)

            item.x = pos.x
            item.y = pos.y

            if (TableManager.gameing) {
                data.realyStatus = 3
            }

            if (TableManager.user === null) {
                node.addChild(item)
                item.getComponent('TablePosManJs').init(data)

            } else {
                if (user[k] && UnitTools.isNullOrUndefined(TableManager.user[k])) {
                    node.addChild(item)
                }
                item.getComponent('TablePosManJs').init(data)
            }
        }
    }

    // 更新人物节点
    static updateFigureNode (user, node, prefab) {
        cc.log('更新人物')
        for (let nk in node.children) {
            for (let uk in user) {
                if (node.children[nk].uid == user[uk]['uid']) {
                    let playerNode = node.children[nk].getChildByName('PlayerInfo')
                    let layoutNode = playerNode.getChildByName('layout')
                    let nodeObj = {
                        betValue: layoutNode.getChildByName('curValue'),
                        blnValue: layoutNode.getChildByName('balanceValue'),
                        readly: layoutNode.getChildByName('readlyStatus')
                    }
                    let labelObj = {
                        bet: nodeObj.betValue.getComponent(cc.Label),
                        bln: nodeObj.blnValue.getComponent(cc.Label),
                        readly: nodeObj.readly.getComponent(cc.Label)
                    }

                    if (TableManager.gameing) {
                        nodeObj.readly.active = false
                    } else {
                        nodeObj.readly.active = true
                    }

                    labelObj.bet.string = user[uk]['bet']+' '
                    labelObj.bln.string = user[uk]['balance']+' '
                    let readlyTxt = ''
                    if (user[uk]['status'] == 0) {
                        readlyTxt = '未准备'
                    } else if (user[uk]['status'] == 1) {
                        readlyTxt = '已准备'
                    } else if (user[uk]['status'] == 1) {
                        readlyTxt = '房主'
                    }
                    labelObj.readly.string = readlyTxt
                    break;
                }
            }
        }
    }

    // 移除人物节点
    static rmFigureNode (user, node, prefab) {
        cc.log('移除人物')
        for (let nk in node.children) {
            var flag = false
            for (let uk in user) {
                if (node.children[nk].uid == user[uk]['uid']) {
                    flag = true
                    break
                }
            }
            if (!flag && node.children[nk] != null &&
                !UnitTools.isNullOrUndefined(node.children[nk].uid)) {
                node.removeChild(node.children[nk])
            }
        }
    }

    // 初始化按钮
    static initBtn () {
        TableManager.btnGroupNode = cc.find(TableManager.cardBtnPath)

        for (let i in TableManager.btnGroupNode.children) {
            TableManager.btnGroupNode.children[i].i = i
            TableManager.btnDisable[i] = true
            CreatorHelper.setNodeClickEvent(TableManager.btnGroupNode.children[i], () => {
                if (TableManager.btnDisable[i]) {
                    cc.log('禁用了')
                    return false
                }

                switch (parseInt(i)) {
                    case 0:
                        TableManager.aCard()
                        break
                    case 1:
                        TableManager.seeCard()
                        break
                    case 2:
                        TableManager.disCard()
                        break
                    case 3:
                        TableManager.withCard()
                        break
                    case 4:
                        TableManager.addAmount(0)
                        break
                    case 5:
                        TableManager.allIn()
                        break
                }
            })
        }
    }

    // 禁用按钮
    static disableBtn (pos) {
        if (!TableManager.btnDisable[pos]) {
            var node = TableManager.btnGroupNode.children[pos]
            var btnSprite = node.getComponent(cc.Sprite)
            var path = TableManager.btnBgPath+'banBtn'

            CreatorHelper.changeSpriteFrame(btnSprite, path)
            TableManager.btnGroupNode.children[pos].removeComponent('BtnClick')
            TableManager.btnDisable[pos] = true
        }
    }

    // 启用按钮
    static enableBtn (pos) {
        pos = parseInt(pos)
        if (TableManager.btnDisable[pos]) {
            var node = TableManager.btnGroupNode.children[pos]
            var btnSprite = node.getComponent(cc.Sprite)
            var path = TableManager.btnBgPath+'confirm_bg'
            if (pos === 2) {
                path = TableManager.btnBgPath+'cancel_bg'
            }

            CreatorHelper.changeSpriteFrame(btnSprite, path)
            node.addComponent('BtnClick')
            TableManager.btnDisable[pos] = false
        }
    }

    // 初始化加注按钮
    static initFillBtn () {
        TableManager.btnFillNode = cc.find('Canvas/bg/filling')

        for (let i in TableManager.btnFillNode.children) {
            TableManager.btnFillNode.children[i].i = i
            TableManager.btnFillDisable[i] = true
            CreatorHelper.setNodeClickEvent(TableManager.btnFillNode.children[i], () => {
                if (TableManager.btnFillDisable[i]) {
                    cc.log('禁用了')
                    return false
                }

                switch (parseInt(i)) {
                    case 0:
                        TableManager.addAmount(2)
                        break
                    case 1:
                        TableManager.addAmount(3)
                        break
                    case 2:
                        TableManager.addAmount(5)
                        break
                    case 3:
                        TableManager.addAmount(10)
                        break
                }
            })
        }
    }

    // 禁用加注按钮
    static disableFillBtn (pos) {
        if (!TableManager.btnFillDisable[pos]) {
            var node = TableManager.btnFillNode.children[pos]
            var btnSprite = node.getComponent(cc.Sprite)
            var path = TableManager.btnBgPath+'banBtn'

            CreatorHelper.changeSpriteFrame(btnSprite, path)
            TableManager.btnFillNode.children[pos].removeComponent('BtnClick')
            TableManager.btnFillDisable[pos] = true
        }
    }

    // 启用加注按钮
    static enableFillBtn (pos) {
        pos = parseInt(pos)
        if (TableManager.btnFillDisable[pos]) {
            var node = TableManager.btnFillNode.children[pos]
            var btnSprite = node.getComponent(cc.Sprite)
            var path = TableManager.btnBgPath+'confirm_bg'

            CreatorHelper.changeSpriteFrame(btnSprite, path)
            node.addComponent('BtnClick')
            TableManager.btnFillDisable[pos] = false
        }
    }

    // 退出牌桌
    static exitTable (uid, tid) {
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.playerLeaveTable(uid, tid, (res) => {
                if (res.ok && res.code === 200) {
                    cc.log('退出房间成功')
                    TableManager.user = null
                    cc.director.loadScene('hall')
                } else {
                    TableManager.alertModel(res.msg)
                }
            })
        })
    }

    // 获取游戏基本信息
    static getGameStartInfo (uid, tid) {
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.getGameStartBaseInfo(uid, tid, (res) => {
                if (res.ok && res.code === 200 && !UnitTools.isNullOrUndefined(res.datas)) {
                    let obj = JSON.parse(res.datas)

                    UserManager.hands = obj.hands
                    UserManager.pos = obj.pos
                    UserManager.flows = obj.flows
                    TableManager.isNeedAutoACard()
                    TableManager.realTimeAddHandsCard()
                    TableManager.setOperFlows()
                    TableManager.setFillFlows()
                } else {
                    cc.log('获取手牌信息失败')
                }
            })
        })
    }

    // 重新开始游戏，手牌关闭掉
    static handsReStart () {
        var canvas = cc.find('Canvas')
        for (let pos = 0; pos < 5; pos++) {
            var pnode = cc.find('bg/CardsContainer'+pos, canvas)
            if (pnode !== null) {
                var card = 0
                for (let i = 0; i < 5; i++) {
                    var childNode = pnode.getChildByName('Card'+i)
                    childNode.active = false
                }
            }
        }
    }

    // 动态添加手牌
    static realTimeAddHandsCard () {
        var canvas = cc.find('Canvas')
        cc.log('手牌信息:', UserManager.hands)
        for (let pos in UserManager.hands) {
            var pnode = cc.find('bg/CardsContainer'+pos, canvas)

            if (pnode !== null) {
                var length = UserManager.hands[pos].length
                var card = 0

                for (let i in UserManager.hands[pos]) {
                    if (UserManager.hands[pos][i].status === true) {
                        card = parseInt(UserManager.hands[pos][i].card)
                    } else {
                        card = 0
                    }

                    var childNode = pnode.getChildByName('Card'+i)
                    childNode.active = true
                    var sprite = childNode.getComponent(cc.Sprite)
                    var cardPath = 'images/bigimages/cards'
                    CreatorHelper.changeSpriteAtlas(sprite, cardPath, card)
                }
            }
        }
    }

    // 设置操作模式
    static setOperFlows () {
        cc.log('操作流程:', UserManager.flows)
        if (!UnitTools.isNullOrUndefined(UserManager.flows) ||
            UserManager.flows != '[]') {
            var flows = UserManager.flows[UserManager.pos].oper
            cc.log('操作模式:', flows)
            for (let i in flows) {
                if (flows[i] == 1) {
                    TableManager.enableBtn(i)
                } else {
                    TableManager.disableBtn(i)
                }
            }
        }
    }

    // 设置加注模式
    static setFillFlows () {
        var fill = UserManager.flows[UserManager.pos].fill
        cc.log('加注模式:', fill)
        for (let i in fill) {
            if (fill[i] == 1) {
                TableManager.enableFillBtn(i)
            } else {
                TableManager.disableFillBtn(i)
            }
        }
    }

    // 获取总投注
    static getTotalBet (userlist) {
        let total = 0
        for (let i in userlist) {
            total += userlist[i].bet
        }
        return total
    }

    // 结算当前牌局
    static settlementCurMatch () {
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.settlementCurMatch(UserManager.myuid, UserManager.tid, (res) => {
                cc.log('结算当前牌局:', res)
            })
        })
    }

    // 获取当前牌局结果
    static getCurMatchResults () {
        var canvas = cc.find('Canvas')
        var path = 'prefabs/settlement/table'

        TableManager.btnGroupNode.active = false // 隐藏按钮组
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.getCurMatch(UserManager.myuid, UserManager.tid, (res) => {
                if (res.code === 200 && res.ok) {
                    var obj = JSON.parse(res.datas)
                    var pos = 0

                    for (let i in obj) {
                        if (obj[i].uid == UserManager.myuid) {
                            pos = i
                            if (obj[i].win <= 0) {
                                TableManager.LoseModel.active = true
                            } else {
                                TableManager.WinModel.active = true
                            }
                        }
                    }
                    if (TableManager.LoseModel.active) {
                        var content = TableManager.LoseModel.getChildByName('content')
                        var activeNode = TableManager.LoseModel.getChildByName('activebg')
                    } else {
                        var content = TableManager.WinModel.getChildByName('content')
                        var activeNode = TableManager.LoseModel.getChildByName('activebg')
                    }

                    content.removeAllChildren()
                    CreatorHelper.loadPrefab(path, (node) => {
                        var name = node.getChildByName('name')
                        var win = node.getChildByName('win')
                        var nameTxt = name.getComponent(cc.Label)
                        var winTxt = win.getComponent(cc.Label)

                        nameTxt.string = '昵称'
                        winTxt.string = '输赢'
                        content.addChild(node)

                        var counnt = 0
                        for (let i in obj) {
                            if (obj[i].uid == UserManager.myuid) {
                                var curPos = TableManager.settlementPos(counnt)
                                activeNode.y = parseInt(curPos.y)
                            }
                            counnt++

                            CreatorHelper.loadPrefab(path, (node) => {
                                var name = node.getChildByName('name')
                                var win = node.getChildByName('win')
                                var nameTxt = name.getComponent(cc.Label)
                                var winTxt = win.getComponent(cc.Label)

                                nameTxt.string = obj[i].username
                                winTxt.string = obj[i].win
                                content.addChild(node)
                            })
                        }
                    })
                    cc.log('当前牌局结果:', obj)
                }
            })
        })
    }

    // 结算解散房间
    static allLeaveRoom () {
        TableManager.LoseModel.active = false
        TableManager.WinModel.active = false
        TableManager.alertModel('牌桌局数结束，即将离开牌桌')
        UserManager.flows = null
        UserManager.pos = null
        UserManager.hands = null
        setTimeout(() => {
            cc.director.loadScene('hall')
        }, 2000)
    }

    // 结算退出游戏
    static settlementAfterExitGame () {
        TableManager.LoseModel.active = false
        TableManager.WinModel.active = false
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.settlementAfterExitGame(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    cc.director.loadScene('hall')
                } else {
                    TableManager.alertModel(res.msg)
                }
            })
        })
    }

    // 结算继续游戏
    static settlementAfterStartGame () {
        if (TableManager.LoseModel != undefined &&
            TableManager.WinModel != undefined) {
            TableManager.LoseModel.active = false
            TableManager.WinModel.active = false
        }

        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.settlementAfterStartGame(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    cc.log('继续游戏:', res)
                } else {
                    TableManager.alertModel(res.msg)
                    setTimeout(() => {
                        cc.director.loadScene('hall')
                    }, 2000)
                }
            })
        })
    }

    // 判断是否需要自动过牌
    static isNeedAutoACard () {
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.isAutoACard(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    TableManager.autoACard()
                } else {
                    cc.log('判断自动过牌:', res)
                }
            })
        })
    }

    // 自动过牌
    static autoACard () {
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.autoACard(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    cc.log('自动过牌成功:', res)
                } else {
                    cc.log('自动过牌失败:', res)
                }
            })
        })
    }

    // 过牌
    static aCard () {
        TableManager.btnFillNode.active = false
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.aCard(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    let obj = JSON.parse(res.datas)
                    cc.log('过牌成功:', obj)
                } else {
                    cc.log('过牌失败:', res)
                    TableManager.alertModel(res.msg)
                }
            })
        })
    }

    // 看牌
    static seeCard () {
        TableManager.btnFillNode.active = false
        var pos = UserManager.pos
        var canvas = cc.find('Canvas')
        var pnode = cc.find('bg/CardsContainer'+pos, canvas)
        var childNode = pnode.getChildByName('Card'+0)
        var sprite = childNode.getComponent(cc.Sprite)
        var cardPath = 'images/bigimages/cards'
        var card = parseInt(UserManager.hands[pos][0].card)
        CreatorHelper.changeSpriteAtlas(sprite, cardPath, card)

        setTimeout(() => {
            CreatorHelper.changeSpriteAtlas(sprite, cardPath, 0)
        }, 5000)
    }

    // 弃牌
    static disCard () {
        TableManager.btnFillNode.active = false
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.disCard(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    let obj = JSON.parse(res.datas)
                    cc.log('弃牌成功:', obj)
                } else {
                    cc.log('弃牌失败:', res)
                    TableManager.alertModel(res.msg)
                }
            })
        })
    }

    // 跟牌
    static withCard () {
        TableManager.btnFillNode.active = false
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.withCard(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    let obj = JSON.parse(res.datas)
                    cc.log('跟牌成功:', obj)
                } else {
                    cc.log('跟牌失败:', res)
                    TableManager.alertModel(res.msg)
                }
            })
        })
    }

    // 加注
    static addAmount (type) {
        if (type === 0) {
            TableManager.btnFillNode.active = !TableManager.btnFillNode.active
        } else {
            NetworkManager.onConnectedToGame((gameService) => {
                gameService.proxy.fill(UserManager.myuid, UserManager.tid, type, (res) => {
                    if (res.ok && res.code === 200) {
                        TableManager.btnFillNode.active = false
                        let obj = JSON.parse(res.datas)
                        cc.log('加注成功:', obj)
                    } else {
                        cc.log('加注失败:', res)
                        TableManager.alertModel(res.msg)
                    }
                })
            })
        }
    }

    // 梭哈
    static allIn () {
        TableManager.btnFillNode.active = false
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.allin(UserManager.myuid, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    let obj = JSON.parse(res.datas)
                    cc.log('梭哈成功:', obj)
                } else {
                    cc.log('梭哈失败:', res)
                    TableManager.alertModel(res.msg)
                }
            })
        })
    }
}

// 时钟路径
TableManager.clockPath = 'prefabs/table/Clock'

// 牌路径
TableManager.cardPath = 'prefabs/table/Card'

// 牌容器路径
TableManager.cardContainerPath = 'prefabs/table/CardContainer'

// 操作路径
TableManager.cardBtnPath = 'Canvas/bg/btnGroup'

// 按钮背景图片资源
TableManager.btnBgPath = 'images/smallimages/model/'

// 按钮组节点
TableManager.btnGroupNode = null

// 加注按钮组节点
TableManager.btnFillNode = null

// 按钮组禁用状态
TableManager.btnDisable = [ false, false, false, false, false, false ]

// 加注按钮组禁用状态
TableManager.btnFillDisable = [ false, false, false, false ]

// 牌桌user信息
TableManager.user = null

// 牌桌游戏状态
TableManager.gameing = false

// 结算状态
TableManager.settlement = false

module.exports = TableManager
